<?php
namespace App\Http\Controllers\Admin;

use App\Models\Company;
use App\Models\CompanyScale;
use App\Models\CompanyDevelop;
use App\Models\Tags;
use App\Models\CompanyAuth;
use App\Http\Requests\CompanyPostRequest;
use Illuminate\Support\Facades\Auth;
use App\Models\CompanyTags;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;
use App\Models\Area;
use App\Models\CompanyAddress;
use App\Models\CompanyTypeLink;
use App\Models\CompanyType;
use Illuminate\Support\Facades\DB;
use App\Models\CompanyJobs;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use App\Commands\CompanyArea;
use App\Models\ImportArea;
use App\Models\CompanyJobsType;
use App\User;
use App\Models\Role;

/**
 *
 * @author Joker
 *
 */
class CompanyController extends BaseController
{

    protected $area;
    
    protected $types;
    
    private $error;
    private $errMsg;
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        // TODO: Auto-generated method stub
        parent::__construct();
        $this->error = false;
        $this->area= Area::where('pid','=',0)->orderBy('sort','ASC')->get();
        $this->types = CompanyType::where('parent_id','=',0)->orderBy('sort','ASC')->get();
    }
    
    /**
     *  企业首页
     */
    public function index(Request $req)
    {
        if(!$this->user->can('viewCompany')) abort(405);
        Queue::later(30, new CompanyArea());
        $title = $req->input('title');
        $username = $req->input('username');
        $nowtype = $req->input('type');
        $query = Company::whereIn('is_validate',[1,2]);
        if($title)
            $query->where('name','like','%'.$title.'%');
        if($username)
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('created_uid',$authorids);
        }
        if($nowtype)
        {
            $query->leftJoin('company_type_link','company.id','=','company_type_link.company_id')
                  ->where('company_type_link.type_id','=',$nowtype);
        }
        $company = $query->orderBy('created_at','desc')->orderBy('id','desc')->paginate(20);
        
        return view('admin.enterprise.company.index')->with('company',$company)->with('types',$this->types)->with('nowtype',$nowtype)
                ->with('title',$title)->with('username',$username);
    }

    public function noverify(Request $req)
    {
        if(!$this->user->can('viewCompany')) abort(405);
        $title = $req->input('title');
        $username = $req->input('username');
        $nowtype = $req->input('type');
        
        $query = Company::where('is_validate','=',0);
        if($title)
            $query->where('name','like','%'.$title.'%');
        if($username)
        {
            $authorids = User::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('created_uid',$authorids);
        }
        if($nowtype)
        {
            $query->leftJoin('company_type_link','company.id','=','company_type_link.company_id')
            ->where('company_type_link.type_id','=',$nowtype);
        }
        $company = $query->orderBy('created_at','desc')->orderBy('id','desc')->paginate(20);
        return view('admin.enterprise.company.index')->with('company',$company)->with('types',$this->types)->with('nowtype',$nowtype)
                ->with('title',$title)->with('username',$username);
    }
    
    /**
     * 企业详情页面
     */
    public function show($id)
    {
        if(\Illuminate\Support\Facades\Request::ajax())
        {
            if(!$this->user->can('viewCompany')) 
                return $this->formatJson('error',$this->permerror);
        }
        else 
        {
            if(!$this->user->can('viewCompany')) abort(405);
        }
        
        $company = Company::where('id','=',$id)->first();
        $scales = CompanyScale::all();
        $develops = CompanyDevelop::all();
        $authes = CompanyAuth::all();
        $result = $company->tags;
        $tags = array();
        if(count($result)>0)
        {
            foreach ($result as $res)
            {
                $tags[] = Tags::where('tags_id','=',$res->tags_id)->first()->tags_name;
            }
        }
        //begin by hex 2015-11-15 新增返回地址 子级区域信息
        $company->comtype = array_fetch($company->types->toArray(),'type_id');
        $address = $company->addressinfo;
        $subarea= Area::where('pid','=',$address->province)->orderBy('sort','ASC')->get();
        $thrarea= Area::where('pid','=',$address->city)->orderBy('sort','ASC')->get();
        if(\Illuminate\Support\Facades\Request::ajax())
        {
            $company->newsTag = $tags;
            return $this->formatJson('success','获取信息成功',$company);
        }
        else 
        {
            //end
            return view('admin.enterprise.company.details')
                    ->with('result',$company)
                    ->with('develops',$develops)
                    ->with('newstag',implode(",", $tags))
                    ->with('authes',$authes)
                    ->with('blademode','edit')
                    ->with('area',$this->area)
                    ->with('subarea',$subarea)
                    ->with('thrarea',$thrarea)
                    ->with('scales',$scales)
                    ->with('types',$this->types)
                    ->with('address',$address);
        }
       
    }

    /**
     * 企业新增
     */
    public function create()
    {
        if(!$this->user->can('editCompany')) abort(405);
        
        $scales = CompanyScale::all();
        $develops = CompanyDevelop::all();
        $authes = CompanyAuth::all();

        return view('admin.enterprise.company.details')
            ->with('develops',$develops)
            ->with('authes',$authes)
            ->with('blademode','add')
            ->with('area',$this->area)
            ->with('types',$this->types)
            ->with('scales',$scales);
    }

    /**
     * 企业信息保存
     */
    public function store(CompanyPostRequest $req) 
    {
        if(!$this->user->can('editCompany')) 
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('name','signature','logo','intro','email','phone','main_page','develop','investment',
            'scale','authtype','tagsinput','tel','zip_code','bus_route','user_id','blademode','company_id','add_id','province','city','area',
            'address','longitude','latitude','ctype','nature');
        
        if($data['blademode'] == 'edit' && is_numeric($data['company_id']) && $data['company_id'] > 0 && is_numeric($data['add_id']) && $data['add_id'] > 0)
        {
            $company = Company::find($data['company_id']);
            $address = CompanyAddress::find($data['add_id']);
        }
        else
        {
            $company = new Company();
            $address = new CompanyAddress();
            $company->is_validate = 1;
            $company->validated_at = date('Y-m-d H:i:s');
        }

        $tagids =array();
        $tags = strToArray($data['tagsinput'], ",");
        foreach ($tags as $tg){
            if(!empty(trim($tg)))
            {
                $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                $tagids[] = $tagsModel->tags_id;
            }
        }
        
        $company->name = $data['name'];
        $company->signature = $data['signature'];
        $company->logo = $data['logo'];
        $company->intro = $data['intro'];
        $company->email = $data['email'];
        $company->phone = $data['phone'];
        $company->main_page = $data['main_page'];
        $company->scale_id = $data['scale'];
        $company->develop_id = $data['develop'];
        $company->investment = $data['investment'];
        $company->auth_id = $data['authtype'];
        $company->logo = $data['logo'];
        $company->tel = $data['tel'];
        $company->zip_code = $data['zip_code'];
        $company->bus_route = $data['bus_route'];
        $company->nature = $data['nature'];
        $company->updated_user_id = $data['user_id']==Auth::user()->id ? $data['user_id'] :Auth::user()->id;
        
        DB::beginTransaction();
        try {
            $company->save();
            //begin by hex 2015-11-15 新增地址信息保存
            $address->company_id = $company->id;
            $address->province = $data['province'];
            $address->city = $data['city'];
            $address->area = $data['area'];
            $address->address = $data['address'];
            $address->longitude = $data['longitude'];
            $address->latitude = $data['latitude'];
            $address->save();
            //end
            CompanyTags::where('company_id','=',$company->id)->delete();
            foreach ($tagids as $tgd){
                CompanyTags::firstOrCreate(['tags_id'=>$tgd,'company_id'=>$company->id]);
            }
            
            $ctype = $data['ctype'];
            CompanyTypeLink::where('company_id','=',$company)->delete();
            foreach ($ctype as $ctp)
            {
                CompanyTypeLink::firstOrCreate(['company_id'=>$company->id,'type_id'=>$ctp]);
            }
        }catch (\PDOException $e){
            DB::rollback();
            return $this->formatJson('falied','企业数据保存失败！');
        }
        DB::commit();
        return Response::json(array('id'=>$company->id,'status'=>'success','msg'=>'保存数据成功！','redirectUrl'=>'/admin/enterprise/companys'));
    }
    
    /**
     * 企业 推荐至充电加油 企业专区 模块
     */
    public function companyTeaches(Request $req)
    {
        if(!$this->user->can('editCompany')) 
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('is_disabled','id');
        $company = Company::find($data['id']);
        $is_teaches = $data['is_disabled'] == 0 ? 1 : 0;
        $company->is_teaches = $is_teaches;
        $company->teachesed();
        return  Response::json(array('status'=>'success','msg'=>'推荐成功', 'data' => $is_teaches));
    }

    /**
     * 企业审核
     */
    public function companyValidate(Request $req)
    {
        if(!$this->user->can('editCompany'))
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('is_validate','id');
        if(empty($data['is_validate']))
        {
            return $this->formatJson('error','请选择审核结果！');
        }
        $company = Company::find($data['id']);
        $company->is_validate = $data['is_validate'];
        $company->validated();
        return $this->formatJson('success',"企业： ".$company->name." 审核成功！",$company,'/admin/enterprise/noverify');
        if($company->is_validate == 1)
            return $this->formatJson('success',"文章：［ ".$company->name." ］审核通过！",$company,'/admin/enterprise/noverify');
        else if($company->is_validate == 2)
            return $this->formatJson('success',"文章：［ ".$company->name." ］不通过！",$company,'/admin/enterprise/noverify');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteCompany'))
            return $this->formatJson('error',$this->permerror);
        
        $company = Company::find($id);
        DB::beginTransaction();
        try{
                //删除企业相关的主要附属信息 标签、类型、地址
            CompanyTags::where('company_id', '=', $id)->delete();
            CompanyTypeLink::where('company_id', '=', $id)->delete();
            CompanyAddress::where('company_id', '=', $id)->delete();
            CompanyJobs::where('company_id','=',$id)->delete();
            $company->delete();
            DB::commit();
        }catch (\PDOException $e){
            DB::rollback();
            return $this->formatJson('falied','企业删除失败');
        }
       
        return  Response::json(array('status'=>'success','msg'=>'企业［'.$company->name.'］删除成功!'));
    }

    
    /**
     * 导入企业信息
     * 以及相关职位 
     */
    public function import(Request $request)
    {
        if(!$this->user->can('editTeachesOrganization'))
            return $this->formatJson('error',$this->permerror);
        
        /*excel上传处理*/
        $file = $request->file('upfile');
        $base_dir = public_path('uploads/exports/company');
        if($file->isValid()){
            $clientName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $newName = md5(date('ymdhis').$clientName).".".$extension;
            $file->move($base_dir,$newName);
        }
        else
        {
            return Response::json(array('url'=>'','status'=>'false','msg'=>'上传文件失败！'));
        }
        $file_path = public_path('uploads/exports/company/'.$newName);
        
        Excel::selectSheetsByIndex(0)->load($file_path, function($reader)
        {
            $insert_company = array();
            foreach ($reader->noHeading()->get()->toArray() as $key => $row) 
            {
                if($key > 0)
                {
                    $insert_company['name'] = trim($row[0]);
                    $company = Company::where('name','=',$insert_company['name'])->first();
                    $types = array();
                    $company_types = strToArray(trim($row[1]),"/");
                    if(!empty($company_types))
                    {
                        foreach ($company_types as $ctp)
                        {
                            if(!empty(trim($ctp)))
                            {
                                $companyType =CompanyType::where('name','=',$ctp)->first();
                                if(empty($companyType))
                                {
                                    $this->error = true;
                                    $this->errMsg = '行业分类［'.$ctp.']不存在,请在行业分类中增加后，再试。';
                                    return false;
                                }
                                $types[] = $companyType->id;
                            }
                        }
                    }
                    else
                    {
                        $this->error = true;
                        $this->errMsg = '企业［'.$insert_company['name'].'］行业分类不可为空!';
                        return false;
                    }
                    $insert_company['intro'] = $row[2];
                    $insert_company['email'] = trim($row[3]);
                    $hasEmail = Company::where('email','=',$insert_company['email'])->where('name','<>',$insert_company['name'])->first();
                    if(empty($insert_company['email']) || !empty($hasEmail))
                    {
                        $this->error = true;
                        $this->errMsg = '企业［'.$insert_company['name'].'］邮箱已存在!';
                        return false;
                    }
                    $insert_company['tel']   = trim($row[4]);
                    $insert_company['nature']= trim($row[5]);
                    $scales_id = CompanyScale::where('name','=',trim($row[6]))->pluck('id');
                    if($scales_id == 0 || empty($scales_id))
                    {
                        $this->error = true;
                        $this->errMsg = '企业［'.$insert_company['name'].'］规模［'.$row[6].']不存在!';
                        return false;
                    }
                    $insert_company['scale_id'] = $scales_id;
                    $insert_company['zip_code'] = trim($row[7]);
                    $tagids =array();
                    $tags = strToArray($row[12], "/");
                    foreach ($tags as $tg){
                        if(!empty(trim($tg)))
                        {
                            $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                            $tagids[] = $tagsModel->tags_id;
                        }
                    }
                    $username = trim($row[13]);
                    $insert_user = array(
                        'name'      => $username,
                        'password'  => bcrypt('cimors123'),
                        'email'     => $insert_company['email']
                    );
                    $insert_company['is_validate'] = 1;
                    $insert_company['validated_at'] = date('Y-m-d H:i:s');
                    DB::beginTransaction();
                    try{
                        $companyUser = User::withTrashed()->where(['name'=>$username,'email'=>$insert_company['email']])->first();
                        if(!$companyUser)
                        {
                            $companyUser = User::firstOrCreate($insert_user);
                            $userRole = Role::where('name','=','company')->first();
                            $companyUser->attachRole($userRole);
                        }
                        
                        $insert_company['created_uid'] = $companyUser->id;
                        if(empty($company))
                        {
                            $company = Company::firstOrCreate($insert_company);
                        }
                        else
                        {
                            foreach ($insert_company as $key=>$inc)
                            {
                                $company->$key = $inc;
                            }
                            $company->save();
                        }
                        $deleteWhere = ['company_id'=>$company->id];
                        CompanyTags::where($deleteWhere)->delete();
                        foreach ($tagids as $tgd){
                            CompanyTags::firstOrCreate(['tags_id'=>$tgd,'company_id'=>$company->id]);
                        }
                        CompanyTypeLink::where($deleteWhere)->delete();
                        foreach ($types as $ctp)
                        {
                            CompanyTypeLink::firstOrCreate(['company_id'=>$company->id,'type_id'=>$ctp]);
                        }
                        $area_row = array(
                            'company_id'    => $company->id,
                            'province'      => trim($row[8]), 
                            'city'          => trim($row[9]), 
                            'area'          => trim($row[10]),
                            'address'       => trim($row[11])
                        );
                        ImportArea::firstOrCreate($area_row);
                        $companyUser->restore();
                        $companyUser->update($deleteWhere);
                        DB::commit();
                    }catch (\PDOException $e){
                        Log::info(['批量导入企业信息异常'=>$e->getMessage()]);
                        DB::rollBack();
                        $this->error = true;
                        $this->errMsg = '企业批量导入异常错误!';
                        return false;
                    }
                }
            }
        });
        if($this->error)
        {
            return $this->formatJson('error',$this->errMsg);
        }
        //职位导入
        Excel::selectSheetsByIndex(1)->load($file_path, function($reader)
        {
            $insert_job = array();
            foreach ($reader->noHeading()->get()->toArray() as $key => $row) 
            {
                if($key > 0)
                {
                    $insert_job['title'] = trim($row[0]);
                    $companyname = trim($row[1]);
                    if(empty($companyname))
                    {
                        $this->error = true;
                        $this->errMsg = '职位［'.$insert_job['title'].'］的企业为空，请修改。';
                        return false;
                    }
                    $company = Company::where('name','=',$companyname)->first();
                    if(empty($company))
                    {
                        $this->error = true;
                        $this->errMsg = '职位［'.$insert_job['title'].'］企业［'.$companyname.'］不存在，请修改。';
                        return false;
                    }
                    $jobs = CompanyJobs::where(['title'=>$insert_job['title'],'company_id'=>$company->id])->first();
                    if(empty($jobs))
                    {
                        $insert_job['company_id'] = $company->id;
                        $first_cat = CompanyJobsType::where('name','=',trim($row[2]))->first();
                        if(empty($first_cat))
                        {
                            $this->error = true;
                            $this->errMsg = '职位［'.$insert_job['title'].'］一级分类［'.$row[2].'］不存在，请修改。';
                            return false;
                        }
                        $second_cat = CompanyJobsType::where(['name'=>trim($row[3]),'parent_id'=>$first_cat->cat_id])->first();
                        if(empty($second_cat))
                        {
                            $this->error = true;
                            $this->errMsg = '职位［'.$insert_job['title'].'］二级分类［'.$row[3].'］不存在，请修改。';
                            return false;
                        }
                        $insert_job['cat_id'] = CompanyJobsType::where(['name'=>trim($row[4]),'parent_id'=>$second_cat->cat_id])->pluck('cat_id');
                        if(empty($insert_job['cat_id']))
                        {
                            $this->error = true;
                            $this->errMsg = '职位［'.$insert_job['title'].'］分类［'.$row[4].'］不存在，请修改。';
                            return false;
                        }
                        $salary =  strToArray(trim($row[5]), "-");
                        $insert_job['salary_lower'] = str_replace("k", "", $salary[0]);
                        $insert_job['salary_high'] = str_replace("k", "", $salary[1]);
                        $degree = array(0=>'大专',1=>'本科',2=>'硕士',3=>'博士',4=>'其他',5=>'不限');
                        $gznx = array(0=>'应届毕业生',1=>'1年以下',2=>'1-3年',3=>'3-5年',4=>'5-10年',5=>'10年以上',6=>'不限');
                        $gzxz = array(0=>'全职',1=>'兼职',2=>'实习');
                        $jobDegree = $jobGznx = $jobGzxz = 0;
                        foreach ($degree as $key=>$dg)
                        {
                            if($dg == trim($row[6]))
                                $jobDegree = $key;
                        }
                        foreach ($gznx as $key=>$val)
                        {
                            if($val == trim($row[7]))
                                $jobGznx = $key;
                        }
                        foreach ($gzxz as $key=>$val)
                        {
                            if($val == trim($row[8]))
                                $jobGzxz = $key;
                        }
                        $insert_job['degree'] = $jobDegree;
                        $insert_job['gznx']   = $jobGznx;
                        $insert_job['gzxz']   = $jobGzxz;
                        $insert_job['intro']  = $row[9];
                        $insert_job['description'] = $row[10];
                        $insert_job['recruitment'] = $row[11];
                        $insert_job['area'] = Area::where('title','=',trim($row[12]))->pluck('area_id');
                        if(empty($insert_job['area']))
                        {
                            return $this->formatJson('error','工作地点不可为空！');
                        }
                        $insert_job['status'] = 1;
                        $insert_job['validated_at'] = date("Y-m-d H:i:s");
                        $insert_job['user_id'] = $this->user->id;
                        DB::beginTransaction();
                        try {
                            $jobs = CompanyJobs::firstOrCreate($insert_job);
                            $company->incrementAdd('jobs_count',1);
                            DB::commit();
                        }catch (\PDOException $e){
                            Log::info(['批量导入职位异常'=>$e->getMessage()]);
                            DB::rollBack();
                            $this->error = true;
                            $this->errMsg = '职位［'.$insert_job['title'].'］数据异常。';
                            return false;
                        }
                    }
                }
            }
        });
        if($this->error)
        {
            return $this->formatJson('error',$this->errMsg);
        }
        return $this->formatJson('success','导入成功！');
    }
}